import json
import re
import random

from django import http
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection

from libs.captcha.captcha import captcha
from users.models import User


class ImageCodeView(View):
    def get(self,request):
        cur_id=request.GET.get('cur')
        # print(cur_id)
        _,text,image_data=captcha.generate_captcha()

        #2 存储图片验证码的值到redis中
        redis_conn=get_redis_connection('code')
        redis_conn.set('image_code_%s'%cur_id,text,60)
        # pass
        return http.HttpResponse(image_data,content_type='image/png')



class SMSCodeView(View):
    def post(self,request):
        #1,获取参数
        mobile=json.loads(request.body.decode()).get('mobile')
        if User.objects.filter(mobile=mobile).count()>0:
            return http.JsonResponse({'errno': 4001, 'errmsg': '手机号码已注册'})
        image_code=json.loads(request.body.decode()).get('text')
        image_code_id=json.loads(request.body.decode()).get('id')

        redis_conn = get_redis_connection('code')
        send_flag=redis_conn.get('send_flag_%s'% mobile)
        if send_flag:
            return http.JsonResponse({'errno':4001,'errmsg':'短信验证码不可重复获取'})
        #2,校验参数
        #2,1 为空校验
        if not all([image_code,image_code_id]):
            return http.JsonResponse({'errno': 4001, 'errmsg': '参数不全'})
        if not re.match(r'^1[3-9]\d{9}$',mobile):
            return http.JsonResponse({'errno': 4001, 'errmsg': '手机格式错误'})

        redis_conn=get_redis_connection('code')
        redis_image_code=redis_conn.get('image_code_%s' % image_code_id)
        if not redis_image_code:
            return http.JsonResponse({"errno": 4001, "errmsg": "图片验证码已过期"})
        if image_code.upper()!=redis_image_code.decode().upper():
            return http.JsonResponse({'errno': 4001, 'errmsg': '图片验证码填写错误'})
        #3,发送短信,数据入库
        sms_code='%06d'%random.randint(0,999999)
        # result = CCP().send_template_sms(mobile, [sms_code, 5], 1)
        # if result == -1:
        #     return http.JsonResponse({'code':4001,'errmsg':'短信发送失败'})

        # send_message(mobile,sms_code)
        print(sms_code)
        #保存短信验证码到redis,方便之后判断短信的正确性
        redis_conn.set('sms_code_%s'%mobile,sms_code,300)

        #设置标记，防止一分钟之内，多次发送短信
        redis_conn.set('send_flag_%s'%mobile,1,60)

        #4,返回响应
        return http.JsonResponse({'errno':'0'})